import { EggLogger } from 'egg';
import { Inject, HTTPController, HTTPMethod, HTTPMethodEnum, Context, EggContext, Middleware, HTTPBody, HTTPQuery } from '@eggjs/tegg';
import { responseFormatter } from 'app/middleware/responseFormatter';
import { AddWorkshopOptions, UpdateWorkshopOptions } from 'typings/app/workshop';
import { EggAppConfig } from 'typings/app';
import { toInt } from 'app/libs/utils';
import { group } from 'radash';

@HTTPController({
  path: '/workshop',
})
@Middleware(responseFormatter)
export class WorkshopController {
  @Inject()
  logger: EggLogger;
  @Inject()
  config: EggAppConfig;

  @HTTPMethod({
    method: HTTPMethodEnum.POST,
    path: '/updateWorkshop',
  })
  async updateWorkshop(@Context() ctx: EggContext, @HTTPBody() workshop: UpdateWorkshopOptions) {
    await ctx.model.Workshop.update(workshop, {
      where: { id: workshop.id },
    });
    return {};
  }

  @HTTPMethod({
    method: HTTPMethodEnum.DELETE,
    path: '/deleteWorkshop',
  })
  async deleteWorkshop(@Context() ctx: EggContext, @HTTPQuery() id: number) {
    const workshop = await ctx.model.Workshop.findByPk(id);
    await workshop.destroy();
    return {};
  }

  @HTTPMethod({
    method: HTTPMethodEnum.POST,
    path: '/addWorkshop',
  })
  async addWorkshop(@Context() ctx: EggContext, @HTTPBody() workshop: AddWorkshopOptions) {
    const currWorkshop = await ctx.model.Workshop.findOne({
      where: { name: workshop.name, factory_id: workshop.factoryId },
    });
    if (currWorkshop) {
      ctx.throw({
        code: 1001,
        message: '添加失败，当前工厂存在同名的车间！',
      });
    }
    await ctx.model.Workshop.create(workshop);
    return {};
  }

  @HTTPMethod({
    method: HTTPMethodEnum.GET,
    path: '/getWorkshopOptions',
  })
  async getWorkshopOptions(@Context() ctx: EggContext) {
    const sql = `SELECT a.id, a.name, b.name as factoryName, b.id as factoryId
    FROM bordsys_workshop_test as a
    LEFT JOIN bordsys_factory_test as b ON a.factory_id = b.id ORDER BY a.factory_id;`;
    const [ list, , ] = await ctx.model.query(sql);
    return group(list, (item: any) => item.factoryId);
  }

  @HTTPMethod({
    method: HTTPMethodEnum.GET,
    path: '/getWorkshopList',
  })
  async getWorkshopList(@Context() ctx: EggContext) {
    const { page, limit } = ctx.query;
    const offset = (toInt(page) * toInt(limit)) as number;
    const sql = `SELECT a.*, b.name as factoryName
    FROM bordsys_workshop_test as a
    LEFT JOIN bordsys_factory_test as b ON a.factory_id = b.id ORDER BY a.factory_id OFFSET ${offset} ROWS
    FETCH NEXT ${limit} ROWS ONLY;`;
    const total = await ctx.model.Workshop.count();
    const [ list, , ] = await ctx.model.query(sql);
    return { list, total };
  }
}
